package Timer;

import java.util.PriorityQueue;

public class MyTimer {

    private final PriorityQueue<MyTask> queue = new PriorityQueue<>();

    public void schedule(Runnable runnable,long time){

        synchronized (queue){
            MyTask myTask = new MyTask(runnable,time);
            queue.offer(myTask);
            queue.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread(()->{
           while (true){
               synchronized (queue){
                   if (queue.isEmpty()){
                       try {
                           queue.wait();
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
                   MyTask myTask = queue.peek();
                   long curTime = System.currentTimeMillis();
                   if (myTask.time <= curTime){
                       //时间到了，考可以执行任务了
                       myTask.runnable.run();
                       queue.poll();
                   }else {
                       try {
                           queue.wait(myTask.time - curTime);
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
               }
           }
        });
        thread.start();
    }
}
